package com.imu.wys.aop;

import com.imu.wys.model.User;
import com.imu.wys.service.UserService;
import com.imu.wys.util.RedisUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;

@Component
@Aspect
public class ControllerAspect {
    @Autowired
    UserService userService;

    @Autowired
    RedisUtil redisUtil;
    @AfterReturning(value = "execution(* com.imu.wys.controller.UserControllerCache.*(..))", returning = "result")
    public void afterReturning(JoinPoint point, Object result) {
        String msg = (String) ((ModelAndView) result).getModel().get("msg");
        User user = (User) ((ModelAndView) result).getModel().get("user");
        String methodName = point.getSignature().getName();
        System.out.println(methodName);
        if (user != null) {//操作成功
            if (methodName.equals("login")) {
                userService.insertUserLog(user, "登录成功");
            } else if (methodName.equals("register")) {
                userService.insertUserLog(user, "注册成功");
            }

        } else {//登录失败
            if (methodName.equals("login")) {
                Object[] args = point.getArgs();
                User user1 = new User();
                user1.setUsername(args[1].toString());
                userService.insertUserLog(user1, "登录失败");
                String key = "loginErrorKey"+user1.getUsername();
                String shixiaoKey = "shiXiaoKey"+user1.getUsername();
                System.out.println(key);
                if(redisUtil.getExpire(shixiaoKey)>0){
                    return;
                }
                if(redisUtil.hasKey(key)){
                    if((int)redisUtil.get(key)==2){

                        redisUtil.set(shixiaoKey,"1");
                        redisUtil.expire(shixiaoKey,60);
                        redisUtil.del(key);
                    }else{
                        redisUtil.set(key,(int)redisUtil.get(key)+1);
                    }

                }else {
                    redisUtil.set(key,1);
                }
            }
        }
    }


    @Before(value = "execution(* com.imu.wys.controller.UserControllerCache.login(..))")
    public void beforeLogin(JoinPoint point) {
        Object[] args = point.getArgs();
        String username = args[1].toString();


    }
}
